(function(){
	var AjaxCrud = QualityCheck.AjaxCRUD;
	var serverUrl = QualityCheck.GPUD.ServiceConfig;
	var currentPage = 1;
//	var pageSize = 10;
	var map = null;
	var toolbar = null;
	var scale = null;
	var editorTool = {};
	var circle = {};
	var mySlider;
	var style = {
	        color:'#FC740F',
	        fillColor:'#FC740F',
	        fillOpacity:0.2,
	        weight:3
	    };
	var styleselect = {
	        color:'#00ABF0',
	        fillColor:'#00ABF0',
	        fillOpacity:0.2,
	        weight:3
	    };
	$(function(){
		var usercode = $("#user-name",parent.parent.document).attr("code");
		var userkey = $("#user-name",parent.parent.document).attr("key");
		var usertype = $("#user-name",parent.parent.document).attr("usertype");
		keyCheck(usercode,usertype,userkey,function(){
			window.onresize = function () {
				initFencePages();
				initMap();
				fenceEditPageBtns();
				getSchoolFence();
			};
			initFencePages();
			initMap();
			fenceEditPageBtns();
			getSchoolFence();
		});
	});
	function initMap(){
		map = new AMap.Map("map",{
			level:15,//设置地图缩放级别
			/*center:new AMap.LngLat(116.397428,39.90923),//设置地图中心点	
*/			});
		map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
			toolbar = new AMap.ToolBar();
			toolbar.autoPosition=false; //加载工具条 
			map.addControl(toolbar);  	
			scale = new AMap.Scale(); //加载比例尺
			map.addControl(scale);
		});
		map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
		$(".amap-logo").hide();
		$(".amap-copyright").hide();
		$(".amap-container").css("position","absolute");
	}
	function getSchoolFence(){
		var userKey = $("#user-name",parent.parent.document).attr("key");
    	var data = {
				cmd:"getSchoolByPage",
				model:"school",
				userKey:userKey,
				data:{
					currentpage : currentPage,
//					pagesize : pageSize
				},
				remark:""
				
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			for(var key in circle){
				circle[key].setMap(null);
			}
			circle = {};
			if(res.result == 1 && res.data != undefined && res.data != ""){
				showFenceList(res);
				var list = res.data.data;
				for(var i = 0; i < list.length; i++){
					var fencepoint = list[i].center.split(",");
					var x = fencepoint[0] * 1;
					var y = fencepoint[1] * 1;
					var fenceradius = list[i].radius;
					var schoolcode = list[i].schoolcode;
					addCircle(schoolcode,new AMap.LngLat(x,y),fenceradius*100,style,list[i]);
				}
			}
		},null,null);
    }
	function drawCircle(name,latlng,radius,options){
		if(circle[name]){
			circle[name].setMap(null);
			circle[name] = null;
		}
		circle[name] = new AMap.Circle({
			id:name,
			center:latlng,//圆心，基点
			radius:radius,//半径
			strokeColor: options.color,//线颜色
			strokeOpacity: 1,//线透明度
			strokeWeight: 3,//线宽
			fillColor: options.fillColor,//填充颜色
			fillOpacity: 0.2//填充透明度
		});
		circle[name].setMap(map);
		//添加编辑控件
		map.plugin(["AMap.CircleEditor"], function() {
			editorTool["new"] = new AMap.CircleEditor(map, circle["new"]);	
			editorTool["new"].open();
			AMap.event.addListener(editorTool["new"], "adjust", function(e){
				if(Math.round(e.radius) < 100){
					e.radius = 100;
				}else if(Math.round(e.radius) > 500){
					e.radius = 500;
				}else{
					e.radius = (Math.round(e.radius/100))*100;
				}
				mySlider.setValue(e.radius);
				$("#fence-radius").val(Math.round(e.radius));
			});
			AMap.event.addListener(editorTool["new"], "move", function(e){
				var lng = e.lnglat.lng;
				var lat = e.lnglat.lat;
				var latLng =lng + "," + lat;
				$("#fence-center").val(latLng);
			});
		});
	}
	function addCircle(name,latlng,radius,options,attr){
		if(circle[name]){
			circle[name].setMap(null);
			circle[name] = null;
		}
		circle[name] = new AMap.Circle({
			id:name,
			center:latlng,//圆心，基点
			radius:radius,//半径
			strokeColor: options.color,//线颜色
			strokeOpacity: 1,//线透明度
			strokeWeight: 3,//线宽
			fillColor: options.fillColor,//填充颜色
			fillOpacity: 0.2//填充透明度
		});
		circle[name].setExtData({attr:attr});
		circle[name].setMap(map);
		AMap.event.addListener(circle[name],"click",function(e){
			$(".fence-table-tr").removeClass("fence-table-tr-sel");
			$(".fence-table-tr[fencename='"+name+"']").addClass("fence-table-tr-sel");
			clearSelect(name);
			circle[name].setOptions({
				fillColor:styleselect.fillColor,
				strokeColor:styleselect.color
			});
			//添加编辑控件
			if(editorTool[name] == undefined){
				map.plugin(["AMap.CircleEditor"], function() {
					editorTool[name] = new AMap.CircleEditor(map, circle[name]);
				});
			}
			editCircle(circle[name],circle[name].getExtData().attr,editorTool[name]);
		});
	}
	function editCircle(circle,options,edit){
		$(".fence-edit-btn").unbind("click");
		$(".fence-edit-btn").click(function(){
			fenceEditBtnClick(circle,options,edit);
		});
		$(".fence-delete-btn").unbind("click");
		$(".fence-delete-btn").click(function(){
			var schoolcode = options.schoolcode;
			deleteBox("确定要删除吗？",function(){
				deleteSchoolFence(schoolcode);
			});
		});
	}
	function fenceEditBtnClick(circle,options,edit){
		showEditDialog(options);
		map.plugin(["AMap.CircleEditor"], function(){
			edit = editorTool[name] = new AMap.CircleEditor(map, circle);
			edit.open();
			AMap.event.addListener(edit, "adjust", function(e){
				if(Math.round(e.radius) < 100){
					e.radius = 100;
				}else if(Math.round(e.radius) > 500){
					e.radius = 500;
				}else{
					e.radius = (Math.round(e.radius/100))*100;
				}
				mySlider.setValue(e.radius);
				$("#fence-radius").val(Math.round(e.radius));
			});
			AMap.event.addListener(edit, "move", function(e){
				var lng = e.lnglat.lng;
				var lat = e.lnglat.lat;
				var latLng =lng + "," + lat;
				$("#fence-center").val(latLng);
			});
		});
		mySlider.attachEvent("onChange", function(value){
			circle.setRadius(value);
			$("#fence-radius").val(value);
		});
		mySlider.attachEvent("onSlideEnd", function(value){
			circle.setRadius(value);
			$("#fence-radius").val(value);
		});
		editCircle(circle,options,edit);
	}
	function showEditDialog(options){
		var contents = "<table class='fence-table'>" +
							"<tr><td>中心点</td><td><input type='text' id='fence-center' value='"+options.center+"'></td></tr>" +
							"<tr><td>半径</td><td><div id=\"sliderObj\"></div><input type='text' id='fence-radius' value='"+(options.radius)*100 +"'>米</td></tr>" +
							"<tr><td>名称</td><td><input type='text' id='fence-name' value='"+options.name+"''></td></tr>" +
							"<tr><td>编码</td><td><input type='text' id='fence-schoolcode' value='"+options.schoolcode+"''></td></tr>" +
							"<tr><td>地址</td><td><input type='text' id='fence-adress' value='"+options.adress+"'></td></tr>" +
							"<tr><td>备注</td><td><input type='text' id='fence-remark' value='"+options.remark+"' style='width: 190px;height: 20px;line-height: 20px;margin:0;'></td></tr>" +
						"</table>" +
						"<div class='fence-edit-save'>保存</div>";
		var obj = {
					disable:false,
					width:315,
					height:305,
					title:"编辑围栏"+options.remark,
					left:325,
					top:50,
					contents:contents
				  };
		showDialog(obj);
		newMySlider();
		mySlider.setValue((options.radius)*100);
		$(".fence-edit-save").unbind("click");
		$(".fence-edit-save").click(function(){
			if($("#fence-schoolcode").val() != ""){
				var obj = {};
				obj.center = $("#fence-center").val();
				obj.radius = $("#fence-radius").val()/100;
				obj.name = encodeURI($("#fence-name").val());
				obj.schoolcode = $("#fence-schoolcode").val();
				obj.adress = encodeURI($("#fence-adress").val());
				obj.remark = encodeURI($("#fence-remark").val());
				updateSchoolFence(obj);
			}else{
				$("#fence-schoolcode").attr("placeholder","学校编码不能为空");
				return false;
			}
		});
		$(".index-dialog-close").unbind("click");
		$(".index-dialog-close").click(function(){
			$(".index-dialog").hide();
			for(var key in editorTool){
				editorTool[key].close();
			}
			clearAll();		
			$(".data-trs-show").removeClass("data-trs-show-selected");
		});
		
	}
	function clearAll(){
		for(var key in circle){
			circle[key].setOptions({
				fillColor:style.fillColor,
				strokeColor:style.color
			});
			
		}
	}
	function clearSelect(name){
		for(var key in circle){
			if(key != name && key != "new"){
				circle[key].setOptions({
					fillColor:style.fillColor,
					strokeColor:style.color
				});
			}
		}
	}
	function newMySlider(){
		mySlider = new dhtmlXSlider({
			parent: "sliderObj",
			linkTo: "fence-radius",
			size: 150,
			value: 5,
			step: 100,
			min: 100,
			max: 500
		});
	}
    //页面所有按钮绑定事件
    function fenceEditPageBtns(){
    	$(".fence-add-btn").click(function(){
    		var contents = "<table class='fence-table'>" +
								"<tr><td>中心点</td><td><input type='text' id='fence-center'></td></tr>" +
								"<tr><td>半径</td><td><div id=\"sliderObj\"></div><input type='text' id='fence-radius'>米</td></tr>" +
								"<tr><td>名称</td><td><input type='text' id='fence-name'></td></tr>" +
								"<tr><td>编码</td><td><input type='text' id='fence-schoolcode'></td></tr>" +
								"<tr><td>地址</td><td><input type='text' id='fence-adress'></td></tr>" +
								"<tr><td>备注</td><td><input type='text' id='fence-remark'' style='width: 190px;height: 20px;line-height: 20px;margin:0;'></td></tr>" +
							"</table>" +
							"<div class='fence-add-save'>保存</div>";
    		var obj = {
    					disable:false,
    					width:315,
    					height:305,
    					title:"添加围栏",
    					left:325,
    					top:50,
    					contents:contents
    				  };
    		showDialog(obj);
    		newMySlider();
    		var mapClick = AMap.event.addListener(map, "click", function(e){
    			var lngd = e.lnglat.lng;
    			var latd = e.lnglat.lat;
    			var latLngd =lngd + "," + latd;
    			$("#fence-center").val(latLngd);
    			AMap.event.removeListener(mapClick);
    			drawCircle('new',new AMap.LngLat(lngd,latd), 100, style);
    			mySlider.attachEvent("onChange", function(value){
    				circle["new"].setRadius(value);
    				$("#fence-radius").val(value);
    			});
    			mySlider.attachEvent("onSlideEnd", function(value){
    				circle["new"].setRadius(value);
    				$("#fence-radius").val(value);
    			});
    			$(".fence-add-save").unbind("click");
    			$(".fence-add-save").click(function(){
    				if($("#fence-schoolcode").val() != ""){
    					var obj = {};
    					obj.center = $("#fence-center").val();
    					obj.radius = $("#fence-radius").val()/100;
    					obj.name = encodeURI($("#fence-name").val());
    					obj.schoolcode = $("#fence-schoolcode").val();
    					obj.adress = encodeURI($("#fence-adress").val());
    					obj.remark = encodeURI($("#fence-remark").val());
    					addSchoolFence(obj);
    				}else{
    					$("#fence-schoolcode").attr("placeholder","学校编码不能为空");
    					return false;
    				}
    			});
    			$(".index-dialog-close").unbind("click");
    			$(".index-dialog-close").click(function(){
    				$(".index-dialog").hide();
    				editorTool["new"].close();
    				circle["new"].setMap(null);
    				
    			});
    		});
    		
    	});
    	$(".fence-edit-btn").click(function(){
    		alertBox("unedselect","请先选中一个围栏再进行编辑",true);
    	});
    	$(".fence-delete-btn").click(function(){
    		alertBox("undeselect","请先选中一个围栏再进行删除操作",true);
    	});
    }
    function showFenceList(res){
    	var content = "<table class='fence-res-data' style='border-collapse:collapse;'>" +
    				  "<tr class='fence-data-title'><td>序号</td><td>名称</td><td>地址</td><tr>";
    	if(res.result == 1 && res.data != undefined && res.data != ""){
    		var list = res.data.data;
    		for(var i = 0; i < list.length; i++){
    			content += "<tr fencename='"+list[i].schoolcode+"' schoolcode='"+ list[i].schoolcode +"' latlng = '"+list[i].center+"' class='fence-table-tr'>" +
    			"<td>" + (i+1) + "</td>" +
    			"<td title='" + list[i].name + "'>" + subStrings(list[i].name) + "</td>" +
    			"<td title='" + list[i].adress + "'>" + subStrings(list[i].adress) + "</td>" +
    			"</tr>";
    		}
    	}else{
    		content += "<tr class='no-res-text'><td colspan='3'>未查询到结果！</td></tr>";
    	}
    	content += "</table>";
    	$(".quality-left-page-content").empty();
		$(".quality-left-page-content").append(content);
    	
    	$(".fence-table-tr").unbind("click");
    	$(".fence-table-tr").click(function(){
    		$(".fence-table-tr").removeClass("fence-table-tr-sel");
    		$(this).addClass("fence-table-tr-sel");
    		var latlng = $(this).attr("latlng").split(",");
    		map.panTo(new AMap.LngLat(latlng[0],latlng[1]));
    		var name = $(this).attr("fencename");
    		clearSelect(name);
    		circle[name].setOptions({
				fillColor:styleselect.fillColor,
				strokeColor:styleselect.color
			});
			for(var key in editorTool){
				editorTool[key].close();
			}
			//添加编辑控件
			if(editorTool[name] == undefined){
				map.plugin(["AMap.CircleEditor"], function() {
					editorTool[name] = new AMap.CircleEditor(map, circle[name]);
				});
			}
			fenceEditBtnClick(circle[name],circle[name].getExtData().attr,editorTool[name]);
    	});
    }
   
	function addSchoolFence(obj,name){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"addSchoolInfo",
				model:"school",
				userKey:userKey,
				data:obj,
				remark:""
				
		};
		processBegin("正在添加···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("添加学校围栏成功");
				editorTool["new"].close();
				map.off("click");
				closeDialog(function(){
					for(var key in circle){
						circle[key].setMap(null);
					}
					circle = {};
					getSchoolFence();
				});
				//showAddSchoolManager(name,obj.schoolcode);
			}else{
				processError("添加学校围栏失败");
			}
		},null,null);
	}
//	function addSchoolManager(obj){
//		var userKey = $("#user-name",parent.parent.document).attr("key");
//		var data = {
//				cmd:"register",
//				model:"user",
//				userKey:userKey,
//				data:obj,
//				remark:""
//				
//		};
//		processBegin("正在添加···");
//		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
//			if(res.result == 1 && res.data != undefined && res.data != ""){
//				processEnd("添加校管理员成功");
//				closeDialog(function(){
//					getSchoolFence();
//				});
//			}else{
//				processError("添加校管理员失败");
//			}
//		},null,null);
//	}
	function updateSchoolFence(obj){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"updateSchoolInfo",
				model:"school",
				userKey:userKey,
				data:obj,
				remark:""
				
		};
		processBegin("正在保存···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1){
				processEnd("编辑学校围栏成功");
				closeDialog(function(){
					getSchoolFence();
					for(var key in editorTool){
						editorTool[key].close();
					}
				});
				$(".fence-edit-btn").unbind("click");
				$(".fence-edit-btn").click(function(){
	        		alertBox("unedselect","请先选中一个围栏再进行编辑",true);
	        	});
			}
		},null,null);
	}
	function deleteSchoolFence(schoolcode){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"deleteSchoolInfo",
				model:"school",
				userKey:userKey,
				data:{
					schoolcode:schoolcode
				},
				remark:""
				
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1){
				processEnd("删除学校围栏成功");
				closeDialog(function(){
					for(var key in editorTool){
						editorTool[key].close();
					}
					clearAll();
					getSchoolFence();
				});
				$(".fence-delete-btn").unbind("click");
				$(".fence-delete-btn").click(function(){
	        		alertBox("unedselect","请先选中一个围栏再删除",true);
	        	});
			}
		},null,null);
	}
	function subStrings(str){
		if(str.length > 6){
			str = str.substring(0,5) + "...";
		}
		return str;
	}
//	function showAddSchoolManager(name,schoolcode){
//		var contents = "<table class='fence-table' style='border-collapse:collapse;'>" +
//							"<tr><td>学校名称</td><td><input type='text' id='school-name' schoolcode='"+schoolcode+"' value = '" + name + "'></td></tr>" +
//							"<tr><td>校管理员</td><td><input type='text' id='user_name' value = '" + "" + "'></td></tr>" +
//							"<tr><td>密码</td><td><input type='text' id='user_password' value = '" + "" + "'></td></tr>" +
//						"</table>" +
//						"<div class='fence-add-save' id='save-school-manager'>保存</div>";
//		var obj = {
//					disable:false,
//					width:262,
//					height:280,
//					title:"添加校管理员",
//					left:250,
//					top:140,
//					contents:contents
//				  };
//		showDialog(obj);
//		$(".fence-add-save").unbind("click");
//		$(".fence-add-save").click(function(){
//			if($("#user_name").val() != ""){
//				if($("#user_password").val() != ""){
//					var obj = {};
//    				obj.schoolcode = $("#school-name").attr("schoolcode");
//        			obj.usercode = encodeURI($("#user_name").val());
//        			obj.password = encodeURI($("#user_password").val());
//        			obj.usertype = "0";
//        			obj.islock = "1";
//    				addSchoolManager(obj);
//				}else{
//					$("#user_password").attr("placeholder","密码不能为空");
//					return false;
//				}
//			}else{
//				$("#user_name").attr("placeholder","校管理员不能为空");
//				return false;
//			}
//		});
//	}
	function initFencePages(){
		var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
		$("#map").width(bodyRW);
	}
})();